import os
from data_file_analysis.yaml_analysis import YamlAnalysis as ya
import requests

class TokenOp():

    curpath = os.path.dirname(os.path.realpath(__file__))
    token_yamlpath = os.path.join(curpath, "token.yaml")
    corpid = 'wwfa6fdfb22423e7e1'
    url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'

    @classmethod
    def set_token(cls, app_name=None):
        tokens = ya.parse_yaml(cls.token_yamlpath)

        if(app_name is None or app_name == ''):
            for keys in tokens:
                token_info = tokens[keys]
                secret = token_info['secret']
                r = requests.get(f'{cls.url}?corpid={cls.corpid}&corpsecret={secret}')
                token = str(r.json()['access_token'])
                token_info['token'] = token
        else:
            if app_name in tokens.keys():
                secret = tokens[app_name]['secret']
                r = requests.get(f'{cls.url}?corpid={cls.corpid}&corpsecret={secret}')
                token = str(r.json()['access_token'])
                tokens[app_name]['token'] = token
            else:
                raise Exception(f'key:{app_name} is not in token file!')

        #写到yaml文件中
        ya.write_yaml(cls.token_yamlpath, tokens)

    @classmethod
    def get_token(cls, app_name):
        try:
            token_data = ya.return_yaml_data(cls.token_yamlpath, app_name)
            return token_data['token']
        except Exception as e:
            raise e

if __name__ == '__main__':
    TokenOp().set_token()
    #print(TokenOp().get_token('check_in'))